import requests



import requests
import os

API_KEY = 'AIzaSyASR7YIx67iNi8PS0QeKJol__6sodwNpTU'
CX = 'd25566bd3716d4c6e'
QUERY = 'philippines   sunlight through trees girl'
RESULTS_PER_PAGE = 10
SAVE_DIR = './google_images'

os.makedirs(SAVE_DIR, exist_ok=True)

def fetch_image_links(query, start=1):
    url = 'https://www.googleapis.com/customsearch/v1'
    params = {
        'q': query,
        'cx': CX,
        'key': API_KEY,
        'fileType':'JPEG',
        'searchType': 'image',
        'start': start,
        'num': RESULTS_PER_PAGE,
        'imgSize': 'xlarge',  # 可选：icon, small, medium, large, xlarge
       # 'imgType':'face',
        'safe': 'active'      # 过滤敏感内容
    }
    response = requests.get(url, params=params)
    data = response.json()
    items = data.get('items', [])
    return [item['link'] for item in items]

def download_image(url, folder):
    try:
        response = requests.get(url, timeout=10)
        if response.status_code == 200:
            filename = os.path.join(folder, url.split("/")[-1].split("?")[0])
            with open(filename, 'wb') as f:
                f.write(response.content)
            print(f"Saved: {filename}")
    except Exception as e:
        print(f"Failed to download {url}: {e}")

# 示例：下载前30张图片
for i in range(1, 100, RESULTS_PER_PAGE):
    links = fetch_image_links(QUERY, start=i)
    for link in links:
        download_image(link, SAVE_DIR)

